import React, { useEffect, useState } from 'react';
import { FormProps } from 'tdesign-react';
import { Dialog, Form, Input, Select, InputNumber, Switch, Button, MessagePlugin, Textarea } from 'tdesign-react';
import { JupiterDictionary, JupiterDictionaryForm } from '../../../types/dictionaryTypes';
import { fetchDictionariesByType } from '../../../services/dictionaryService';

interface DictionaryFormProps {
    visible: boolean;
    title: string;
    editingData?: Partial<JupiterDictionary>;
    onClose: () => void;
    onSubmit: (data: JupiterDictionaryForm) => void;
}

export default function DictionaryForm({ visible, title, editingData, onClose, onSubmit }: DictionaryFormProps) {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [dictTypeOptions, setDictTypeOptions] = useState<{ label: string; value: string }[]>([]);

    const getDictTypeOptions = async () => {
        try {
            const response = await fetchDictionariesByType('dict_type');
            if (response.code === 200) {
                const options = response.data.map((item: JupiterDictionary) => ({
                    label: item.dictLabel,
                    value: item.dictKey,
                }));
                setDictTypeOptions(options);
            }
        } catch (error) {
            console.error('获取字典类型选项失败:', error);
        }
    };

    useEffect(() => {
        if (visible) {
            getDictTypeOptions();
            if (editingData) {
                form.setFieldsValue({
                    dictType: editingData.dictType,
                    dictKey: editingData.dictKey,
                    dictValue: editingData.dictValue,
                    dictLabel: editingData.dictLabel,
                    sortOrder: editingData.sortOrder || 0,
                    description: editingData.description,
                    isActive: editingData.isActive !== false,
                });
            } else {
                form.reset();
            }
        }
    }, [visible, editingData, form]);

    const handleSubmit = async () => {
        try {
            const result = await form.validate();
            if (result === true) {
                setLoading(true);
                const formData = form.getFieldsValue(true);
                onSubmit(formData as JupiterDictionaryForm);
            }
        } catch (error) {
            console.error('表单验证失败:', error);
        } finally {
            setLoading(false);
        }
    };


    const handleCancel = () => {
        form.reset();
        onClose();
    };

    return (
        <Dialog
            header={title}
            visible={visible}
            width={600}
            onClose={handleCancel}
            footer={
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                    <Button theme="default" onClick={handleCancel}>
                        取消
                    </Button>
                    <Button theme="primary" loading={loading} onClick={handleSubmit}>
                        确定
                    </Button>
                </div>
            }
        >
            <Form
                form={form}
                labelWidth={100}
                layout="vertical"
            >
                <Form.FormItem
                    label="字典类型"
                    name="dictType"
                    rules={[{ required: true, message: '请选择字典类型' }]}
                >
                    <Select
                        placeholder="请选择字典类型"
                        options={dictTypeOptions}
                        filterable
                        creatable
                    />
                </Form.FormItem>

                <Form.FormItem
                    label="字典键"
                    name="dictKey"
                    rules={[
                        { required: true, message: '请输入字典键' },
                        { max: 128, message: '字典键不能超过128个字符' }
                    ]}
                >
                    <Input placeholder="请输入字典键" />
                </Form.FormItem>

                <Form.FormItem
                    label="字典值"
                    name="dictValue"
                    rules={[
                        { required: true, message: '请输入字典值' },
                        { max: 255, message: '字典值不能超过255个字符' }
                    ]}
                >
                    <Input placeholder="请输入字典值" />
                </Form.FormItem>

                <Form.FormItem
                    label="显示标签"
                    name="dictLabel"
                    rules={[
                        { required: true, message: '请输入显示标签' },
                        { max: 255, message: '显示标签不能超过255个字符' }
                    ]}
                >
                    <Input placeholder="请输入显示标签" />
                </Form.FormItem>

                <Form.FormItem
                    label="排序"
                    name="sortOrder"
                >
                    <InputNumber
                        placeholder="请输入排序值"
                        min={0}
                        max={9999}
                        defaultValue={0}
                    />
                </Form.FormItem>

                <Form.FormItem
                    label="描述"
                    name="description"
                    rules={[{ max: 500, message: '描述不能超过500个字符' }]}
                >
                    <Textarea
                        placeholder="请输入描述"
                        rows={3}
                    />
                </Form.FormItem>

                <Form.FormItem
                    label="是否启用"
                    name="isActive"
                >
                    <Switch />
                </Form.FormItem>
            </Form>
        </Dialog>
    );
}
